<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<button id="btn1" onclick="getAjax()">js-ajax-get</button><br>
	<button id="btn2" onclick="postAjax()">js-ajax-post</button><br>
	<form action="" method="post" enctype="application/x-www-form-urlencoded">
		
	</form>
</body>
<script type="text/javascript">
	//get请求
	function getAjax(){
		//向服务器发送get请求
		//获取xmlhttprequest对象
		var xmlhttp;
		if (window.XMLHttpRequest)
		  {// code for IE7+, Firefox, Chrome, Opera, Safari
		  xmlhttp=new XMLHttpRequest();
		  }
		else
		  {// code for IE6, IE5
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }

		//确定请求方式和请求的路径
		xmlhttp.open("get","${pageContext.request.contextPath}/demo1?username=张三");
		//发送请求
		xmlhttp.send();
		//接收结果(回调函数)
		xmlhttp.onreadystatechange = function(){
			//alert(xmlhttp.readyState);
			//alert(xmlhttp.status);
			if(xmlhttp.readyState==4&&xmlhttp.status==200){
				alert(xmlhttp.responseText);
			}
		}
	}
	
	//post请求
	function postAjax(){
		//向服务器发送post请求
		//获取xmlhttprequest对象
		var xmlhttp;
		if (window.XMLHttpRequest)
		  {// code for IE7+, Firefox, Chrome, Opera, Safari
		  xmlhttp=new XMLHttpRequest();
		  }
		else
		  {// code for IE6, IE5
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }

		//确定请求方式和请求的路径
		xmlhttp.open("post","${pageContext.request.contextPath}/demo1");
		//发送请求
		xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		xmlhttp.send("username=tom");
		//接收结果(回调函数)
		xmlhttp.onreadystatechange = function(){
			//alert(xmlhttp.readyState);
			//alert(xmlhttp.status);
			if(xmlhttp.readyState==4&&xmlhttp.status==200){
				alert(xmlhttp.responseText);
			}
		}
	}
</script>
</html>